package com.zzyl.service.impl;

import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @param
 * @return
 */
@Service
public class MemberServiceImpl implements MemberService {
    //注入微信业务接口
    @Autowired
    private MemberMapper memberMapper;

    //注入微信调用接口
    @Autowired
    private WeChatService weChatService;

    //引入配置类拿到密钥
    @Autowired
    JwtTokenManagerProperties jwtTokenManagerProperties;

    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of(
            "生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意",
            "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝,小波小波耶"
    );

    //登录
    @Override

    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        LoginVo loginVo = new LoginVo();
        //小程序发起登录请求传递code于phonecode,后端拿到code，appid，appsecret向微信调用接口
        //获取openId
        String openid = weChatService.getOpenid(userLoginRequestDto.getCode());
        //获取phone
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());
        //后端根据openId去判断用户是否为空，为空则表示新用户，直接插数据
        Member member = memberMapper.getByOpenId(openid);
        if (member == null) {
            member = new Member();
            //添加openId
            member.setOpenId(openid);
            //添加手机号码
            member.setPhone(phone);
            //是新用户的话就插入到数据库中并给他随机生成昵称
            String name = DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()));
            name = name + "_" + phone.substring(7);
            member.setName(name);
            //调用插入方法
            memberMapper.insertMember(member);// 新用户注册
        } else {
            //不是新用户再判断手机号码是否是同一个
            if (!phone.equals(member.getPhone())) {
                //如果不一致就修改手机号
                member.setPhone(phone);
                memberMapper.updateMember(member);
            }
            loginVo.setNickName(member.getName());
        }

        //一致则表示是老用户，直接登录返回token
        //生成token令牌
        Map map = new HashMap();
        map.put("id", member.getId());
        map.put("nickName", member.getName());
        String token = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(),
                map);
        loginVo.setToken(token);
        return loginVo;
    }
}
